<?php
class StudentsController extends AppController {

	var $name = 'Students';
	var $helpers = array('Html', 'Form');

	function index() {
	//	$this->Student->recursive = 0;
	//	$this->set('students', $this->paginate());


		// для установки факультета и курса
		$this->loadModel('Facultet');
		$facultets = $this->Facultet->find('list');
		$this->set(compact('facultets'));
		$this->loadModel('Profession');
		$selectedprofessions = $this->Profession->find('list');
		$this->set(compact('selectedprofessions'));	
		$this->loadModel('Course');
		$selectedcourses = $this->Course->find('list');
		$this->set(compact('selectedcourses'));	
		$this->loadModel('Studentgroup');		
		$selectedgroups = $this->Studentgroup->find('list');
		$this->set(compact('selectedgroups'));					
		// вывод установки если есть
		// иницилизация переменных настроек
		$selectedfacultet = '';
		$selectedprofession = '';
		$selectedcourse = '';
		$selectedgroup = ''; 
		if ($this->Session->check('Settings')){
			$settings = $this->Session->read('Settings');
			$selectedfacultet = $settings['Settings']['selectedfacultet'];
			$selectedprofession = $settings['Settings']['selectedprofession'];
			$selectedcourse = $settings['Settings']['selectedcourse'];
			$selectedgroup = $settings['Settings']['selectedgroup'];			
		}
		$this->set(compact('selectedfacultet', $selectedfacultet)); 
		$this->set(compact('selectedprofession', $selectedprofession)); 
		$this->set(compact('selectedcourse', $selectedcourse));
		$this->set(compact('selectedgroup', $selectedgroup));
	}
	
	function settings_set() {
		if (!empty($this->data)) {
			$this->Session->delete('Settings');			
			$selectedfacultet = '';
			$selectedprofession = '';
			$selectedcourse = '';
			$selectedgroup = '';
			if ($this->data['Student']['facultet_id']) {
				$selectedfacultet = $this->data['Student']['facultet_id'];
			}
					if ($this->data['Student']['profession_id']) {
				$selectedprofession = $this->data['Student']['profession_id'];
			}
					if ($this->data['Student']['course_id']) {
				$selectedcourse = $this->data['Student']['course_id'];
			}
					if ($this->data['Student']['studentgroup_id']) {
				$selectedgroup = $this->data['Student']['studentgroup_id'];
			}			
			$settings = array('selectedfacultet' => $selectedfacultet,
								'selectedprofession' => $selectedprofession,
								'selectedcourse' => $selectedcourse,
								'selectedgroup' => $selectedgroup);
			$sessionsettings = array ('Settings' => $settings );
			$this->Session->write('Settings', $sessionsettings);
		}
	//	debug($this->data['Student']);
	 	$this->redirect(array('action' => 'index'));
	}

	function settings_unset() {
			if (!empty($this->data)) {
			$this->Session->delete('Settings');
		}
		$this->redirect(array('action' => 'index'));		
	}
		function update_profession () {
		
	  if(!empty($this->data['Student']['facultet_id'])) {
	    $facultet_id = $this->data['Student']['facultet_id'];
	    $this->loadModel('Profession');
	    $options = $this->Profession->find('list', array('conditions' => array ('Profession.facultet_id' => $facultet_id)));
	    $this->set(compact('options'));
	  }	
	}
	
	function update_course () {
	  if(!empty($this->data['Student']['profession_id'])) {
	    $profession_id = $this->data['Student']['profession_id'];
	    $this->loadModel('Course');
	    $options = $this->Course->find('list', array('conditions' => array ('Course.profession_id' => $profession_id)));
	    $this->set(compact('options'));
	  }	
	}

	function update_studentgroup () {
	  if(!empty($this->data['Student']['course_id'])) {
	    $course_id = $this->data['Student']['course_id'];
	    $this->loadModel('Studentgroup');
	    $options = $this->Studentgroup->find('list', array('conditions' => array ('Studentgroup.course_id' =>  $course_id)));
	    $this->set(compact('options'));
	  }	
	}

	function liststudents() {
		$sessionsettings = ''; 
		$selectedfacultet = '';
		$selectedprofession = '';
		$selectedcourse = '';
		$selectedgroup = ''; 
		if ($this->Session->check('Settings')){
			$sessionsettings = $this->Session->read('Settings');
			$selectedfacultet = $sessionsettings['Settings']['selectedfacultet'];
			$selectedprofession = $sessionsettings['Settings']['selectedprofession'];
			$selectedcourse = $sessionsettings['Settings']['selectedcourse'];
			$selectedgroup = $sessionsettings['Settings']['selectedgroup'];			
		}
		$this->set(compact('selectedfacultet', $selectedfacultet)); 
		$this->set(compact('selectedprofession', $selectedprofession)); 
		$this->set(compact('selectedcourse', $selectedcourse));
		$this->set(compact('selectedgroup', $selectedgroup));
		/********************************************************************************************/		
		// выбран факультет спецальность курс группа
		/********************************************************************************************/		
		if ($selectedfacultet && $selectedprofession && $selectedcourse && $selectedgroup) {
			// $students = $this->Student->find('all', array('conditions' => array('Student.studentgroup_id' => $selectedgroup), 'recursive' => 0));
			//формируем массив id групп
			$selectedgroups_ids = array();
			array_push($selectedgroups_ids, $selectedgroup);
		}
		/********************************************************************************************/		
		// выбран факультет специлальность курс
		/********************************************************************************************/		
		else if ($selectedfacultet && $selectedprofession && $selectedcourse && !$selectedgroup) {
			// выбираем группы курса
			$this->loadModel('Studentgroup');
			$selectedgroups = $this->Studentgroup->find('all', array('conditions' => array('Studentgroup.course_id' => $selectedcourse), 
			'recursive' => 0,
			'order' => 'Studentgroup.id ASC',
			'fields' => array('Studentgroup.id')));
			//формируем массив id групп
			$selectedgroups_ids = array();
			foreach ($selectedgroups as $element):
			array_push($selectedgroups_ids, $element['Studentgroup']['id']);
			endforeach;
			// выбираем студентов
		//	$students = $this->Student->find('all', array('conditions' => array('Student.studentgroup_id' => $selectedgroups_ids), 'recursive' => 0));
		}
		/********************************************************************************************/		
		// выбран факультет специальность
		/********************************************************************************************/		
		else if ($selectedfacultet && $selectedprofession && !$selectedcourse && !$selectedgroup) {
			// выбираем курсы специальности
			$this->loadModel('Course');
			$selectedcourses = $this->Course->find('all', array('conditions' => array('Course.profession_id' => $selectedprofession),
			'recursive' => 0,
			'order' => 'Course.id ASC',
			'fields' => array('Course.id')));
			$selectedcourses_ids = array();
			foreach ($selectedcourses as $element):
			array_push($selectedcourses_ids, $element['Course']['id']);
			endforeach;
			// выбираем группы курсов
			$this->loadModel('Studentgroup');
			$selectedgroups = $this->Studentgroup->find('all', array('conditions' => array('Studentgroup.course_id' => $selectedcourses_ids), 
			'recursive' => 0,
			'order' => 'Studentgroup.id ASC',
			'fields' => array('Studentgroup.id')));
			//формируем массив id групп
			$selectedgroups_ids = array();
			foreach ($selectedgroups as $element):
			array_push($selectedgroups_ids, $element['Studentgroup']['id']);
			endforeach;
			// выбираем студентов
		//	$students = $this->Student->find('all', array('conditions' => array('Student.studentgroup_id' => $selectedgroups_ids), 'recursive' => 0));
		}
		/********************************************************************************************/		
		// выбран факультет
		/********************************************************************************************/		
		if ($selectedfacultet && !$selectedprofession && !$selectedcourse && !$selectedgroup) {
			// выбираем специальности факультета
			$this->loadModel('Profession');
			$selectedprofessions = $this->Profession->find('all', array('conditions' => array('Profession.facultet_id' => $selectedfacultet), 'recursive' => 0));
			$selectedprofessions_ids = array();
			foreach ($selectedprofessions as $element):
			array_push($selectedprofessions_ids, $element['Profession']['id']);
			endforeach;			
			// выбираем курсы специальностей
			$this->loadModel('Course');
			$selectedcourses = $this->Course->find('all', array('conditions' => array('Course.profession_id' => $selectedprofessions_ids),
			'recursive' => 0,
	//		'order' => 'Course.id ASC',
			'fields' => array('Course.id')));
			$selectedcourses_ids = array();
			foreach ($selectedcourses as $element):
			array_push($selectedcourses_ids, $element['Course']['id']);
			endforeach;
			// выбираем группы курсов
			$this->loadModel('Studentgroup');
			$selectedgroups = $this->Studentgroup->find('all', array('conditions' => array('Studentgroup.course_id' => $selectedcourses_ids), 
			'recursive' => 0,
	//		'order' => 'Studentgroup.id ASC',
			'fields' => array('Studentgroup.id')));
			//формируем массив id групп
			$selectedgroups_ids = array();
			foreach ($selectedgroups as $element):
			array_push($selectedgroups_ids, $element['Studentgroup']['id']);
			endforeach;
			// выбираем студентов
			// $students = $this->Student->find('all', array('conditions' => array('Student.studentgroup_id' => $selectedgroups_ids), 'recursive' => 0));
			}
		/********************************************************************************************/
		// выбрано все факультеты
		/********************************************************************************************/		
		else if (!$selectedfacultet && !$selectedprofession && !$selectedcourse && !$selectedgroup) {
			//$this->Student->recursive = 0;
			//$students = $this->Student->find('all');
			// выбираем группы курсов
			$this->loadModel('Studentgroup');
			$selectedgroups = $this->Studentgroup->find('all');
			//формируем массив id групп
			$selectedgroups_ids = array();
			foreach ($selectedgroups as $element):
			array_push($selectedgroups_ids, $element['Studentgroup']['id']);
			endforeach;			
		}
		// устнавливем пагинацию
		$this->Student->recursive = 0;
		$conditions =  array('Student.studentgroup_id' => $selectedgroups_ids);
		$this->paginate['conditions'] = $conditions;
		$students = $this->paginate('Student');
		$this->set('students', $students);
		
		// выбираем инфо для заполнения столбцов в таблице
		$this->loadModel('Learningform');
		$learningforms = $this->Learningform->find('list');
		$this->loadModel('Learningtype');
		$this->set('learningforms', $learningforms);
		$learningtypes = $this->Learningtype->find('list');
		$this->set('learningtypes', $learningtypes);
		// id массива professions начинается с 0 так что  чобы получить profession с id = 8 нужно взять 7 элемент массива
		$this->LoadModel('Facultet');
		$facultets = $this->Facultet->find('list');
		$this->set('facultets', $facultets);
		$this->LoadModel('Course');
		$courses = $this->Course->find('all', array('recursive' => 0));
		// id массива courses начинается с 0 так что чтобы получить course с id = 12 нужно взять 11 элемент массива 
		$this->set('courses', $courses);
	}
	
	function tmpgroup() {
		$sessionsettings = ''; 
		$selectedfacultet = '';
		$selectedprofession = '';
		$selectedcourse = '';
		$selectedgroup = ''; 
		if ($this->Session->check('Settings')){
			$sessionsettings = $this->Session->read('Settings');
			$selectedfacultet = $sessionsettings['Settings']['selectedfacultet'];
			$selectedprofession = $sessionsettings['Settings']['selectedprofession'];
			$selectedcourse = $sessionsettings['Settings']['selectedcourse'];
			$selectedgroup = $sessionsettings['Settings']['selectedgroup'];			
		}
		/********************************************************************************************/		
		// выбран факультет спецальность курс группа
		/********************************************************************************************/		
/*		if ($selectedfacultet && $selectedprofession && $selectedcourse && $selectedgroup) {
			// $students = $this->Student->find('all', array('conditions' => array('Student.studentgroup_id' => $selectedgroup), 'recursive' => 0));
			//формируем массив id групп
			$selectedgroups_ids = array();
			array_push($selectedgroups_ids, $selectedgroup);
		}		
		$students = $this->Student->find('all', array('conditions' => array('Student.studentgroup_id' => $selectedgroups_ids), 'recursive' => -1));
	*/	
		$students = $this->Student->find('all');
		$this->set('students', $students);
		//$this->render('/','blank','tmpgroup');
	}
	
	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid Student', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('student', $this->Student->read(null, $id));
	}

	function add() {
		if (!empty($this->data)) {
			$this->Student->create();
			if ($this->Student->save($this->data)) {
				$this->Session->setFlash(__('Студент был добавлен!', true));
				$this->redirect(array('controller' =>'studentinfos', 'action' => 'add/student_id:'.$this->Student->id));
			} else {
				$this->Session->setFlash(__('The Student could not be saved. Please, try again.', true));
			}
		}
	//	$orders = $this->Student->Order->find('list');
	// 	$studentgroups = $this->Student->Studentgroup->find('list');
		$selectedfacultet = '';
		$selectedprofession = '';
		$selectedcourse = '';
		$selectedgroup = ''; 
		if ($this->Session->check('Settings')){
			$settings = $this->Session->read('Settings');
			$selectedfacultet = $settings['Settings']['selectedfacultet'];
			$selectedprofession = $settings['Settings']['selectedprofession'];
			$selectedcourse = $settings['Settings']['selectedcourse'];
			$selectedgroup = $settings['Settings']['selectedgroup'];			
		}
		$this->set(compact('selectedfacultet', $selectedfacultet)); 
		$this->set(compact('selectedprofession', $selectedprofession)); 
		$this->set(compact('selectedcourse', $selectedcourse));
		$this->set(compact('selectedgroup', $selectedgroup));
		// для вывода 
		// для установки факультета и курса
		$this->loadModel('Facultet');
		$selectedfacultets = $this->Facultet->find('list');
		$this->set(compact('selectedfacultets'));
		$this->loadModel('Profession');
		$selectedprofessions = $this->Profession->find('list');
		$this->set(compact('selectedprofessions'));	
		$this->loadModel('Course');
		$selectedcourses = $this->Course->find('list');
		$this->set(compact('selectedcourses'));	
		$this->loadModel('Studentgroup');		
		$selectedgroups = $this->Studentgroup->find('list');
		$this->set(compact('selectedgroups'));		
		// для вывода вариативной части		
		$studentstates = $this->Student->Studentstate->find('list');
		$learningforms = $this->Student->Learningform->find('list');
		$learningtypes = $this->Student->Learningtype->find('list');
		$this->set(compact('orders', 'studentgroups', 'studentstates', 'learningforms', 'learningtypes'));
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid Student', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->data['Student']['studentgroup_id'] == ''){
				$this->data['Student']['studentgroup_id'] = $this->data['Student']['oldstudentgroup_id'];
			}
			if ($this->Student->save($this->data)) {
				$this->Session->setFlash(__('Данные сохранены!', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The Student could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Student->read(null, $id);
		}
		// для установки факультета и курса
		$this->loadModel('Facultet');
		$facultets = $this->Facultet->find('list');
		$this->set(compact('facultets'));		
		$studentstates = $this->Student->Studentstate->find('list');
		$learningforms = $this->Student->Learningform->find('list');
		$learningtypes = $this->Student->Learningtype->find('list');
		$this->set(compact('studentstates', 'learningforms', 'learningtypes'));		
		
		$this->loadModel('Profession');
		$professions = $this->Profession->find('list'); 
		$this->loadModel('Course');
		$courses = $this->Course->find('list');	
		$this->LoadModel('Studentgroup');
		$current_studentgroup = $this->Studentgroup->find('all', array('conditions' => array('Studentgroup.id' => $this->data['Student']['studentgroup_id']), 'recursive' => 0,));
		$this->set('current_studentgroup', $current_studentgroup);	
		//debug($current_studentgroup);	
		$current_profession = $this->Profession->find('all', array('conditions' => array('Profession.id' => $current_studentgroup[0]['Course']['profession_id']), 'recursive' => 0));
		$this->set('current_profession', $current_profession);	
		//debug($current_profession);	
		$this->set(compact('professions', 'courses'));
		// $orders = $this->Student->Order->find('list');
		// $studentgroups = $this->Student->Studentgroup->find('list');
		// $studentstates = $this->Student->Studentstate->find('list');
		// $this->set(compact('orders','studentgroups','studentstates'));
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Student', true));
			$this->redirect(array('action' => 'index'));
		}
		if ($this->Student->del($id)) {
			$this->Session->setFlash(__('Student deleted', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->Session->setFlash(__('The Student could not be deleted. Please, try again.', true));
		$this->redirect(array('action' => 'index'));
	}
	/*
	 *  добавление из csv групп по курсам 
	 */	
	function addgroups () {
		$this->loadModel('Studentgroup');
		// лечебный 
		$year = 2009 ;
		$courses = 6;
		$i = 2;
		$course_id = 2;
		$groups_count = array(22,21,24,19,22);
		$profession_id = 1;
		for ($i=2; $i<=$courses; $i++){
			for ($j=1; $j<=$groups_count[$i-2]; $j++){
				$this->Studentgroup->create();
				$tmp_course_id = $course_id + $i-2;
				if ($j<10){
					$tmp_number = ($year-$i+2).'.0'.$profession_id.'.0'.$j;	
				}
				else {
					$tmp_number = ($year-$i+2).'.0'.$profession_id.'.'.$j;
				}
				$tmp_name = $j.' группа';
				$newdata = array('Studentgroup' => array('course_id' => $tmp_course_id, 'learningform_id'=> 1, 'learningtype_id' => 1, 'number' =>$tmp_number, 'name' => $tmp_name));
			 	$this->Studentgroup->save($newdata);
			//debug ($newdata);
			} 
		}
		// педиатрия
		$year = 2009 ;
		$courses = 6;
		$i = 2;
		$course_id = 9;
		$groups_count = array(5,3,4,4,4);
		$profession_id = 2;
		for ($i=2; $i<=$courses; $i++){
			for ($j=1; $j<=$groups_count[$i-2]; $j++){
				$this->Studentgroup->create();
				$tmp_course_id = $course_id + $i-2;
				if ($j<10){
					$tmp_number = ($year-$i+2).'.0'.$profession_id.'.0'.$j;	
				}
				else {
					$tmp_number = ($year-$i+2).'.0'.$profession_id.'.'.$j;
				}
				$tmp_name = $j.' группа';
				$newdata = array('Studentgroup' => array('course_id' => $tmp_course_id, 'learningform_id'=> 1, 'learningtype_id' => 1, 'number' =>$tmp_number, 'name' => $tmp_name));
			 	$this->Studentgroup->save($newdata);
			//debug ($newdata);
			} 
		}		
		// стоматология 
		$year = 2009 ;
		$courses = 5;
		$i = 2;
		$course_id = 16;
		$groups_count = array(5,5,6,7);
		$profession_id = 3;
		for ($i=2; $i<=$courses; $i++){
			for ($j=1; $j<=$groups_count[$i-2]; $j++){
				$this->Studentgroup->create();
				$tmp_course_id = $course_id + $i-2;
				if ($j<10){
					$tmp_number = ($year-$i+2).'.0'.$profession_id.'.0'.$j;	
				}
				else {
					$tmp_number = ($year-$i+2).'.0'.$profession_id.'.'.$j;
				}
				$tmp_name = $j.' группа';
				$newdata = array('Studentgroup' => array('course_id' => $tmp_course_id, 'learningform_id'=> 1, 'learningtype_id' => 1, 'number' =>$tmp_number, 'name' => $tmp_name));
			 	$this->Studentgroup->save($newdata);
			//debug ($newdata);
			} 
		}		
		// медпроф
		$year = 2009 ;
		$courses = 6;
		$i = 2;
		$course_id = 22;
		$groups_count = array(3,3,3,3,3);
		$profession_id = 4;
		for ($i=2; $i<=$courses; $i++){
			for ($j=1; $j<=$groups_count[$i-2]; $j++){
				$this->Studentgroup->create();
				$tmp_course_id = $course_id + $i-2;
				if ($j<10){
					$tmp_number = ($year-$i+2).'.0'.$profession_id.'.0'.$j;	
				}
				else {
					$tmp_number = ($year-$i+2).'.0'.$profession_id.'.'.$j;
				}
				$tmp_name = $j.' группа';
				$newdata = array('Studentgroup' => array('course_id' => $tmp_course_id, 'learningform_id'=> 1, 'learningtype_id' => 1, 'number' =>$tmp_number, 'name' => $tmp_name));
			 	$this->Studentgroup->save($newdata);
			//debug ($newdata);
			}
		}
		// фармация
		$year = 2009 ;
		$courses = 5;
		$i = 2;
		$course_id = 29;
		$groups_count = array(6,5,5,6);
		$profession_id = 5;
		for ($i=2; $i<=$courses; $i++){
			for ($j=1; $j<=$groups_count[$i-2]; $j++){
				$this->Studentgroup->create();
				$tmp_course_id = $course_id + $i-2;
				if ($j<10){
					$tmp_number = ($year-$i+2).'.0'.$profession_id.'.0'.$j;	
				}
				else {
					$tmp_number = ($year-$i+2).'.0'.$profession_id.'.'.$j;
				}
				$tmp_name = $j.' группа';
				$newdata = array('Studentgroup' => array('course_id' => $tmp_course_id, 'learningform_id'=> 1, 'learningtype_id' => 1, 'number' =>$tmp_number, 'name' => $tmp_name));
			 	$this->Studentgroup->save($newdata);
			//debug ($newdata);
			} 
		}	
		// ЭУЗД
		$year = 2009 ;
		$courses = 5;
		$i = 2;
		$course_id = 35;
		$groups_count = array(2,1,0,2);
		$profession_id = 6;
		for ($i=2; $i<=$courses; $i++){
			for ($j=1; $j<=$groups_count[$i-2]; $j++){
				$this->Studentgroup->create();
				$tmp_course_id = $course_id + $i-2;
				if ($j<10){
					$tmp_number = ($year-$i+2).'.0'.$profession_id.'.0'.$j;	
				}
				else {
					$tmp_number = ($year-$i+2).'.0'.$profession_id.'.'.$j;
				}
				$tmp_name = $j.' группа';
				$newdata = array('Studentgroup' => array('course_id' => $tmp_course_id, 'learningform_id'=> 1, 'learningtype_id' => 1, 'number' =>$tmp_number, 'name' => $tmp_name));
			 	$this->Studentgroup->save($newdata);
			//debug ($newdata);
			} 
		}				
		// клин псих
		$year = 2009 ;
		$courses = 5;
		$i = 2;
		$course_id = 41;
		$groups_count = array(4,3,3,5);
		$profession_id = 7;
		for ($i=2; $i<=$courses; $i++){
			for ($j=1; $j<=$groups_count[$i-2]; $j++){
				$this->Studentgroup->create();
				$tmp_course_id = $course_id + $i-2;
				if ($j<10){
					$tmp_number = ($year-$i+2).'.0'.$profession_id.'.0'.$j;	
				}
				else {
					$tmp_number = ($year-$i+2).'.0'.$profession_id.'.'.$j;
				}
				$tmp_name = $j.' группа';
				$newdata = array('Studentgroup' => array('course_id' => $tmp_course_id, 'learningform_id'=> 1, 'learningtype_id' => 1, 'number' =>$tmp_number, 'name' => $tmp_name));
			 	$this->Studentgroup->save($newdata);
			//debug ($newdata);
			} 
		}			
		// соц работа
		$year = 2009 ;
		$courses = 5;
		$i = 2;
		$course_id = 47;
		$groups_count = array(1,2,2,1);
		$profession_id = 8;
		for ($i=2; $i<=$courses; $i++){
			for ($j=1; $j<=$groups_count[$i-2]; $j++){
				$this->Studentgroup->create();
				$tmp_course_id = $course_id + $i-2;
				if ($j<10){
					$tmp_number = ($year-$i+2).'.0'.$profession_id.'.0'.$j;	
				}
				else {
					$tmp_number = ($year-$i+2).'.0'.$profession_id.'.'.$j;
				}
				$tmp_name = $j.' группа';
				$newdata = array('Studentgroup' => array('course_id' => $tmp_course_id, 'learningform_id'=> 1, 'learningtype_id' => 1, 'number' =>$tmp_number, 'name' => $tmp_name));
			 	$this->Studentgroup->save($newdata);
			//debug ($newdata);
			} 
		}		
		// биотех
		$year = 2009 ;
		$courses = 5;
		$i = 2;
		$course_id = 53;
		$groups_count = array(3,3,3,2);
		$profession_id = 9;
		for ($i=2; $i<=$courses; $i++){
			for ($j=1; $j<=$groups_count[$i-2]; $j++){
				$this->Studentgroup->create();
				$tmp_course_id = $course_id + $i-2;
				if ($j<10){
					$tmp_number = ($year-$i+2).'.0'.$profession_id.'.0'.$j;	
				}
				else {
					$tmp_number = ($year-$i+2).'.0'.$profession_id.'.'.$j;
				}
				$tmp_name = $j.' группа';
				$newdata = array('Studentgroup' => array('course_id' => $tmp_course_id, 'learningform_id'=> 1, 'learningtype_id' => 1, 'number' =>$tmp_number, 'name' => $tmp_name));
			 	$this->Studentgroup->save($newdata);
			//debug ($newdata);
			} 
		}					
		$this->render('/','blank','addgroups');
	}
	/*
	 *  добавление из csv  файла студентов в академе
	 */
	function addakadem (){
		if (!empty($this->data)) {
			// подгружаем модели 
			$this->loadModel('Studentgroup');
			$this->loadModel('Studentinfo');
			$this->loadModel('Targetingintake');
			$this->loadModel('Relative');
			$this->loadModel('PrivilegesStudentinfo');
			// открываем файл
			$csvfile = fopen($this->data["Student"]["csvfile"]["tmp_name"],"r");
			//читаем первую строку там заголовки
			$line = fgetcsv($csvfile, 10000, ";");
			$i=1; 
			$j=1;
			while(!(feof($csvfile))) {
				$is_targetingintake = false;
				$line= fgetcsv($csvfile, 10000, ";");
				/*
				 *  определяем id группы но нашей базе studentgroup_id
				 */
				// определяем id специальности
				if (iconv('Windows-1251', 'UTF-8',trim($line[0])) == 'Лечебный'){
					$profession_id = 1;	
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[0])) == 'Педиатрический'){
					$profession_id = 2;	
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[0])) == 'Стоматологический'){
					$profession_id = 3;	
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[0])) == 'Медико-профилактический'){
					$profession_id = 4;	
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[0])) == 'Фармацевтический'){
					$profession_id = 5;	
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[0])) == 'Экономики и управления здравоохранением'){
					$profession_id = 6;	
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[0])) == 'Клинической психологии'){
					$profession_id = 7;	
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[0])) == 'Социальной работы'){
					$profession_id = 8;	
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[0])) == 'Биотехнологический'){
					$profession_id = 9;	
				} else {
					debug($i.' Не распознан факультет !!!'.iconv('Windows-1251', 'UTF-8',trim($line[0])));
					continue;
				}								
				// line[0] факультет
				// line[1] курс 
				// line[2] группа
				// определяем xxxx.01.01  
				if ($line[1] == 1) {
					$year = 2010;
				} else if ($line[1] == 2) {
					$year = 2009;
				} else if ($line[1] == 3) {
					$year = 2008;
				} else if ($line[1] == 4) {
					$year = 2007;
				} else if ($line[1] == 5) {
					$year = 2006;
				} else if ($line[1] == 6) {
					$year = 2005;
				} else { 
					debug($i.'Не распознан курс '.$line[1]); 
					continue; 
				}
				/*
				 * определяем первую часть NUMBER xxx.0x.
				 * 0 перед profession_id так как пока только 9 специальностей
				 */ 
				// находим id курса для группы академ отпуск
				$tmpcourse = $line[1];							
				$groupcode = 'AA.0'.$profession_id.'.00';	
				
			  	$studentgroup = $this->Studentgroup->find('all', array('conditions' => array('Studentgroup.number' => $groupcode)));
				/*.' '.$studentgroup[0]['Studentgroup']['number']*/
				debug($i.' '.$groupcode.' - курс:'.$studentgroup[$tmpcourse-1]['Studentgroup']['course_id'].' код '.$studentgroup[$tmpcourse-1]['Studentgroup']['number']);
				// определяем бюджет внебюджет
				if (iconv('Windows-1251', 'UTF-8',trim($line[20])) =='Коммерческое') {
					$learningtype_id = 2;
				} else
				if((iconv('Windows-1251', 'UTF-8',trim($line[20])) =='Некомеррческое') || 
					(iconv('Windows-1251', 'UTF-8',trim($line[20])) =='Некомерческое') || 
					(iconv('Windows-1251', 'UTF-8',trim($line[20])) =='Некоммерческое') ||
					(iconv('Windows-1251', 'UTF-8',trim($line[20])) =='Некоммерческое (целевое)')) {
					$learningtype_id = 1;
						if (iconv('Windows-1251', 'UTF-8',trim($line[20])) =='Некоммерческое (целевое)'){
							$is_targetingintake = true ;
						}
					}
				// ******************************
				// пишем запись в модель Student
				// ******************************				
				$this->Student->create();
				$newstudentdata = array('Student' => array(
				'learningform_id' => 1,
				'learningtype_id' => $learningtype_id,
				'studentgroup_id' => $studentgroup[$tmpcourse-1]['Studentgroup']['id'],
				'studentstate_id' => 3,
				'lastname' => iconv('Windows-1251', 'UTF-8',trim($line[3])),
				'firstname' => iconv('Windows-1251', 'UTF-8',trim($line[4])),
				'surname' => iconv('Windows-1251', 'UTF-8',trim($line[5])),
				'unic_number' => ''));
				$this->Student->save($newstudentdata);
				$student_id = $this->Student->id;
				// ******************************
				// записали в Student
				// ******************************
				$enrollment_date = $line[7].'.09.01';
				$this->loadModel('Studentinfo');
				if (iconv('Windows-1251', 'UTF-8',trim($line[27])) == 'ж'){
					$gender_id = 1;
				}else {		$gender_id = 2;	}
				/*
				 * читаем регион сапостовляем id региона
				 */
				if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Архангельская') {
					$region_id = 12;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Белгородская') {
					$region_id = 3; 
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Брянская') {
					$region_id = 2;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Владимирская') {
					$region_id = 13;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Волгоградская') {
					$region_id = 14;	
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Вологодская') {		
					$region_id = 15;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Воронежская') {		
					$region_id = 7;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Гомельская') {		
					$region_id = 16;
				} else 	if ((iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Калинградская')||
							(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Калининградская')||	
							(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Калининрадская'))
				{		
					$region_id = 17;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Калужская') {		
					$region_id = 10;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Камчатская') {		
					$region_id = 18;
				} else 	if ((iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Карачаево-Черкесская республика')||
							(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'КЧР') ||
							(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Карачаево-Черкессия')) {		
					$region_id = 19;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Краснодарский край') {		
					$region_id = 20;
				} else 	if ((iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Красноярский край')||
							(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Кррасноярский край')) {		
					$region_id = 21;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Курская') {		
					$region_id = 1;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Ленинградская') {		
					$region_id = 22;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Липецкая') {		
					$region_id = 6;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Магаданская') {		
					$region_id = 23;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Московская') {		
					$region_id = 9;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Мурманская') {		
					$region_id = 8;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Нижегородская') {		
					$region_id = 24;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Новгородская') {		
					$region_id = 25;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Новосибирская') {		
					$region_id = 26;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Орловская') {		
					$region_id = 4;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Пермская') {		
					$region_id = 27;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Приморский край') {		
					$region_id = 28;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Беларусь') {		
					$region_id = 29;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Дагестан') {		
					$region_id = 30;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Ингушетия') {		
					$region_id = 31;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Коми') {		
					$region_id = 32;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Мари Эл') {		
					$region_id = 33;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Молдова') {		
					$region_id = 34;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Саха (Якутия)') {		
					$region_id = 35;
				} else 	if ((iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Сев. Осетия-Алания') || 
							(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Сев.Осетия - Алания') ||	
							(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Северная Осетия - Алания')||	
							(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'РСО-Алания')){		
					$region_id = 36;
				} else 	if ((iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Ростовкая') || 
							(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Ростовская')){		
					$region_id = 37;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Самарская') {		
					$region_id = 38;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Саратовская') {		
					$region_id = 39;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Сахалинская') {		
					$region_id = 40;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Свердловская') {		
					$region_id = 41;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Смоленская') {		
					$region_id = 42;
				} else 	if ((iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Ставропольский')||
							(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Ставропольский край')) {		
					$region_id = 43;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Тамбовская') {		
					$region_id = 44;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Тверская') {		
					$region_id = 45;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Тульская') {		
					$region_id = 5;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Тюменская') {		
					$region_id = 46;
				} else 	if ((iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Украина')||
							(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Украина, Днепропетровская обл.')) {		
					$region_id = 47;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Хабаровский край') {		
					$region_id = 48;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Ярославская') {		
					$region_id = 49;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Астраханская обл.') {		
					$region_id = 50;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'КБР') {		
					$region_id = 51;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Башкортостан') {		
					$region_id = 52;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Татарстан') {		
					$region_id = 53;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Тыва') {		
					$region_id = 54;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Удмуртия') {		
					$region_id = 55;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Рязанская') {		
					$region_id = 56;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Ульяновская') {		
					$region_id = 57;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Чечня') {		
					$region_id = 58;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Чукотский АО') {		
					$region_id = 59;
				}
				/*
				 *  читаем паспортные данные 
				 *  в аксесовской базе паспартов студентов в академе нету
				 */
				$passport_ser = 'НЕТ ДАННЫХ';
				$passport_num  = 'НЕТ ДАННЫХ';
				$passport_data  = 'НЕТ ДАННЫХ';
				/*if ($line[28]) {
					$passport_ser = iconv('Windows-1251', 'UTF-8',trim($line[28]));
				} else {
					$passport_ser = 'НЕТ ДАННЫХ';
				}
				if ($line[29]) {
					$passport_num  = iconv('Windows-1251', 'UTF-8',trim($line[29]));
				} else {
					$passport_num  = 'НЕТ ДАННЫХ';
				}				
				if ($line[30] || $line[31]) {
				$passport_data = iconv('Windows-1251', 'UTF-8',trim($line[30])).' '.iconv('Windows-1251', 'UTF-8',trim($line[31]));				
				} else {
					$passport_data  = 'НЕТ ДАННЫХ';
				}*/
				/*
				 * читаем образование
				 */
				if (iconv('Windows-1251', 'UTF-8',trim($line[9])) == 'общее среднее') {
					$educationdoctype_id = 1;
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[9])) == 'среднее специальное') {
					$educationdoctype_id  = 3;
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[9])) == 'высшее') {
					$educationdoctype_id = 5;
				}
				/* 
				 * читаем дату рождения
				 */				
				$birthdate = explode('.', $line[6]);
				$birthdate_str = $birthdate[2].'-'.$birthdate[1].'-'.$birthdate[0];
				//debug($birthdate_str);
				// ************************************
				// пишем запись в модель Studentinfo
				// *************************************
				$this->Studentinfo->create();
				$newstudentinfodata = array('Studentinfo' => array(
				'student_id' => $student_id,
				'gender_id' => $gender_id,
				'citizenship_id' => '',
				'region_id' => $region_id,
				'educationdoctype_id' => $educationdoctype_id,
				'foreignlanguage_id' => '',
				'enrollment_date' => $enrollment_date,
				'lastname' => iconv('Windows-1251', 'UTF-8',trim($line[3])),
				'firstname' => iconv('Windows-1251', 'UTF-8',trim($line[4])),
				'surname' => iconv('Windows-1251', 'UTF-8',trim($line[5])),
				'birthdate' => $birthdate_str,
				'passport_ser' => $passport_ser,
				'passport_num' => $passport_num, 
				'passport_data'	=> $passport_data, 
				'passport_birth_place' => '',
				'passport_adress' => iconv('Windows-1251', 'UTF-8',trim($line[12])),
				'adress' => iconv('Windows-1251', 'UTF-8',trim($line[13])),
				'schoolgraduated' => '',
				'educationdocdata' => '',
				'phone' => iconv('Windows-1251', 'UTF-8',trim($line[14])),
				'mobile' => '',
				'email' => '',
				'inn' => '',
				'insurance' => '',
				'pension_certificate' => '',
				'inoculations' => '',
				'moreinfo' => ''));
				$this->Studentinfo->create();
				$this->Studentinfo->save($newstudentinfodata);
				$studentinfo_id = $this->Studentinfo->id;
				//**********************************************************
				// при наличии целевого направления устанавливаем его
				//**********************************************************
				if ($is_targetingintake){
					$newtargetingdata = array('Targetinintake' => array('studentinfo_id' => $studentinfo_id, 
																		'region_id' => $region_id,
																		'info' => 'выгрузка из старой базы'
					));
					$this->Targetingintake->create();
					$this->Targetingintake->save($newtargetingdata);
				}
				//**********************************************************
				// при наличии родителей пишем запись в таблицу relatives
				//**********************************************************
				if ($line[15]){
					$this->Relative->create();
					$newreldata = array('Relative' => array(
					'relativestype_id' => 2,
					'studentinfo_id' => $studentinfo_id,
					'passport_data' => 'НЕТ ДАННЫХ',
					'fio' => iconv('Windows-1251', 'UTF-8',trim($line[15])),
					'job' => iconv('Windows-1251', 'UTF-8',trim($line[16])),
					'jobstatus' =>'',
					'phone' => '',
					'mobile' => '',
					'email' => '',
					'adress' => ''));
					$this->Relative->save($newreldata);
				}
				if ($line[17]) {
					$this->Relative->create();
					$newreldata = array('Relative' => array(
					'relativestype_id' => 1,
					'studentinfo_id' => $studentinfo_id,
					'passport_data' => 'НЕТ ДАННЫХ',
					'fio' => iconv('Windows-1251', 'UTF-8',trim($line[17])),
					'job' => iconv('Windows-1251', 'UTF-8',trim($line[18])),
					'jobstatus' =>'',
					'phone' => '',
					'mobile' => '',
					'email' => '',
					'adress' => ''));
					$this->Relative->save($newreldata);
				}	
				/*
				 * при наличии льгот пишем льготы	
				 */ 
				if ($line[22]){
					$this->PrivilegesStudentinfo->create();
					if ((iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Зона отселения')||
						(iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Постоянно проживающая в зоне отселения')){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 4	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					} else
					if (iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Зона отчуждения'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 8	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					} else	
					if (iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Зона проживания с правом на отселение'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 5	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					} else
					if (iconv('Windows-1251', 'UTF-8',trim($line[17])) == 'Зона с льготным соц.-эконом. статусом'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 6	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					} else		
					if (iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Зона с льготным соц.-эконом. статусом, инвал. 2 гр'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 6	));
						$this->PrivilegesStudentinfo->save($newprivdata);
						$this->PrivilegesStudentinfo->create();
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 1	));					
						$this->PrivilegesStudentinfo->save($newprivdata);							
					} else
					if (iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Инвалид II группы'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 1	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					} else		
					if (iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Инвалид III группы'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 2	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					} else		
					if (iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Инвалид с детства'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 3	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					} else					
					if ((iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Инвалид с детства, Зона с правом на отселение')||
						(iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Зона отселения, Инвалид')){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 3	));
						$this->PrivilegesStudentinfo->save($newprivdata);
						$this->PrivilegesStudentinfo->create();
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 5	));					
						$this->PrivilegesStudentinfo->save($newprivdata);						
					} else		
					if (iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'ребенок-инвалид'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 9	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					} else	
					if (iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Сирота'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 7	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					} else 
					if ((iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Сирота,  зона отселения')||
						(iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Сирота, зона отселения')){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 5	));
						$this->PrivilegesStudentinfo->save($newprivdata);
						$this->PrivilegesStudentinfo->create();
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 7	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					}																		
																									
				}		
				$i++; $j++;				
			}
		}
	//	debug ('всего обработано записей '.$i);
		$this->render('/','blank','addakadem');		
	}
	/*
	 * добавление отчисленных студентов из аксесовской базы
	 */
	function addotchisl() {
			if (!empty($this->data)) {
			// подгружаем модели 
			$this->loadModel('Studentgroup');
			$this->loadModel('Studentinfo');
			$this->loadModel('Targetingintake');
			$this->loadModel('Relative');
			$this->loadModel('PrivilegesStudentinfo');
			// открываем файл
			$csvfile = fopen($this->data["Student"]["csvfile"]["tmp_name"],"r");
			//читаем первую строку там заголовки
			$line = fgetcsv($csvfile, 10000, ";");
			$i=1; 
			$j=1;
			while(!(feof($csvfile))) {
				$is_targetingintake = false;
				$line= fgetcsv($csvfile, 10000, ";");
				/*
				 *  определяем id группы но нашей базе studentgroup_id
				 */
				// определяем id специальности
				if (iconv('Windows-1251', 'UTF-8',trim($line[0])) == 'Лечебный'){
					$profession_id = 1;	
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[0])) == 'Педиатрический'){
					$profession_id = 2;	
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[0])) == 'Стоматологический'){
					$profession_id = 3;	
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[0])) == 'Медико-профилактический'){
					$profession_id = 4;	
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[0])) == 'Фармацевтический'){
					$profession_id = 5;	
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[0])) == 'Экономики и управления здравоохранением'){
					$profession_id = 6;	
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[0])) == 'Клинической психологии'){
					$profession_id = 7;	
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[0])) == 'Социальной работы'){
					$profession_id = 8;	
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[0])) == 'Биотехнологический'){
					$profession_id = 9;	
				} else {
					debug($i.' Не распознан факультет !!!'.iconv('Windows-1251', 'UTF-8',trim($line[0])));
					continue;
				}								
				// line[0] факультет
				// line[1] курс 
				// line[2] группа
				// определяем xxxx.01.01  
				if ($line[1] == 1) {
					$year = 2010;
				} else if ($line[1] == 2) {
					$year = 2009;
				} else if ($line[1] == 3) {
					$year = 2008;
				} else if ($line[1] == 4) {
					$year = 2007;
				} else if ($line[1] == 5) {
					$year = 2006;
				} else if ($line[1] == 6) {
					$year = 2005;
				} else { 
					debug($i.'Не распознан курс '.$line[1]); 
					continue; 
				}
				/*
				 * определяем первую часть NUMBER xxx.0x.
				 * 0 перед profession_id так как пока только 9 специальностей
				 */ 
				// находим id курса для группы академ отпуск
				$tmpcourse = $line[1];							
				$groupcode = 'XX.0'.$profession_id.'.00';	
				
			  	$studentgroup = $this->Studentgroup->find('all', array('conditions' => array('Studentgroup.number' => $groupcode)));
				/*.' '.$studentgroup[0]['Studentgroup']['number']*/
				debug($i.' '.$groupcode.' - курс:'.$studentgroup[$tmpcourse-1]['Studentgroup']['course_id'].' код '.$studentgroup[$tmpcourse-1]['Studentgroup']['number']);
				// определяем бюджет внебюджет
				if (iconv('Windows-1251', 'UTF-8',trim($line[20])) =='Коммерческое') {
					$learningtype_id = 2;
				} else
				if((iconv('Windows-1251', 'UTF-8',trim($line[20])) =='Некомеррческое') || 
					(iconv('Windows-1251', 'UTF-8',trim($line[20])) =='Некомерческое') || 
					(iconv('Windows-1251', 'UTF-8',trim($line[20])) =='Некоммерческое') ||
					(iconv('Windows-1251', 'UTF-8',trim($line[20])) =='Некоммерческое (целевое)')) {
					$learningtype_id = 1;
						if (iconv('Windows-1251', 'UTF-8',trim($line[20])) =='Некоммерческое (целевое)'){
							$is_targetingintake = true ;
						}
					}
				// ******************************
				// пишем запись в модель Student
				// ******************************				
				$this->Student->create();
				$newstudentdata = array('Student' => array(
				'learningform_id' => 1,
				'learningtype_id' => $learningtype_id,
				'studentgroup_id' => $studentgroup[$tmpcourse-1]['Studentgroup']['id'],
				'studentstate_id' => 2,
				'lastname' => iconv('Windows-1251', 'UTF-8',trim($line[3])),
				'firstname' => iconv('Windows-1251', 'UTF-8',trim($line[4])),
				'surname' => iconv('Windows-1251', 'UTF-8',trim($line[5])),
				'unic_number' => ''));
				$this->Student->save($newstudentdata);
				$student_id = $this->Student->id;
				// ******************************
				// записали в Student
				// ******************************
				$enrollment_date = $line[7].'.09.01';
				$this->loadModel('Studentinfo');
				if (iconv('Windows-1251', 'UTF-8',trim($line[27])) == 'ж'){
					$gender_id = 1;
				}else {		$gender_id = 2;	}
				/*
				 * читаем регион сапостовляем id региона
				 */
				if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Архангельская') {
					$region_id = 12;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Белгородская') {
					$region_id = 3; 
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Брянская') {
					$region_id = 2;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Владимирская') {
					$region_id = 13;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Волгоградская') {
					$region_id = 14;	
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Вологодская') {		
					$region_id = 15;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Воронежская') {		
					$region_id = 7;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Гомельская') {		
					$region_id = 16;
				} else 	if ((iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Калинградская')||
							(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Калининградская')||	
							(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Калининрадская'))
				{		
					$region_id = 17;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Калужская') {		
					$region_id = 10;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Камчатская') {		
					$region_id = 18;
				} else 	if ((iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Карачаево-Черкесская республика')||
							(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'КЧР') ||
							(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Карачаево-Черкессия')) {		
					$region_id = 19;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Краснодарский край') {		
					$region_id = 20;
				} else 	if ((iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Красноярский край')||
							(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Кррасноярский край')) {		
					$region_id = 21;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Курская') {		
					$region_id = 1;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Ленинградская') {		
					$region_id = 22;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Липецкая') {		
					$region_id = 6;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Магаданская') {		
					$region_id = 23;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Московская') {		
					$region_id = 9;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Мурманская') {		
					$region_id = 8;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Нижегородская') {		
					$region_id = 24;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Новгородская') {		
					$region_id = 25;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Новосибирская') {		
					$region_id = 26;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Орловская') {		
					$region_id = 4;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Пермская') {		
					$region_id = 27;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Приморский край') {		
					$region_id = 28;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Беларусь') {		
					$region_id = 29;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Дагестан') {		
					$region_id = 30;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Ингушетия') {		
					$region_id = 31;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Коми') {		
					$region_id = 32;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Мари Эл') {		
					$region_id = 33;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Молдова') {		
					$region_id = 34;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Саха (Якутия)') {		
					$region_id = 35;
				} else 	if ((iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Сев. Осетия-Алания') || 
							(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Сев.Осетия - Алания') ||	
							(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Северная Осетия - Алания')||	
							(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'РСО-Алания')){		
					$region_id = 36;
				} else 	if ((iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Ростовкая') || 
							(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Ростовская')){		
					$region_id = 37;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Самарская') {		
					$region_id = 38;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Саратовская') {		
					$region_id = 39;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Сахалинская') {		
					$region_id = 40;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Свердловская') {		
					$region_id = 41;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Смоленская') {		
					$region_id = 42;
				} else 	if ((iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Ставропольский')||
							(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Ставропольский край')) {		
					$region_id = 43;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Тамбовская') {		
					$region_id = 44;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Тверская') {		
					$region_id = 45;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Тульская') {		
					$region_id = 5;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Тюменская') {		
					$region_id = 46;
				} else 	if ((iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Украина')||
							(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Украина, Днепропетровская обл.')) {		
					$region_id = 47;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Хабаровский край') {		
					$region_id = 48;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Ярославская') {		
					$region_id = 49;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Астраханская обл.') {		
					$region_id = 50;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'КБР') {		
					$region_id = 51;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Башкортостан') {		
					$region_id = 52;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Татарстан') {		
					$region_id = 53;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Тыва') {		
					$region_id = 54;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Удмуртия') {		
					$region_id = 55;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Рязанская') {		
					$region_id = 56;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Ульяновская') {		
					$region_id = 57;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Чечня') {		
					$region_id = 58;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Чукотский АО') {		
					$region_id = 59;
				}
				/*
				 *  читаем паспортные данные 
				 *  в аксесовской базе паспартов студентов в академе нету
				 */
				$passport_ser = 'НЕТ ДАННЫХ';
				$passport_num  = 'НЕТ ДАННЫХ';
				$passport_data  = 'НЕТ ДАННЫХ';
				/*if ($line[28]) {
					$passport_ser = iconv('Windows-1251', 'UTF-8',trim($line[28]));
				} else {
					$passport_ser = 'НЕТ ДАННЫХ';
				}
				if ($line[29]) {
					$passport_num  = iconv('Windows-1251', 'UTF-8',trim($line[29]));
				} else {
					$passport_num  = 'НЕТ ДАННЫХ';
				}				
				if ($line[30] || $line[31]) {
				$passport_data = iconv('Windows-1251', 'UTF-8',trim($line[30])).' '.iconv('Windows-1251', 'UTF-8',trim($line[31]));				
				} else {
					$passport_data  = 'НЕТ ДАННЫХ';
				}*/
				/*
				 * читаем образование
				 */
				if (iconv('Windows-1251', 'UTF-8',trim($line[9])) == 'общее среднее') {
					$educationdoctype_id = 1;
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[9])) == 'среднее специальное') {
					$educationdoctype_id  = 3;
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[9])) == 'высшее') {
					$educationdoctype_id = 5;
				}
				/* 
				 * читаем дату рождения
				 */				
				$birthdate = explode('.', $line[6]);
				$birthdate_str = $birthdate[2].'-'.$birthdate[1].'-'.$birthdate[0];
				//debug($birthdate_str);
				// ************************************
				// пишем запись в модель Studentinfo
				// *************************************
				$this->Studentinfo->create();
				$newstudentinfodata = array('Studentinfo' => array(
				'student_id' => $student_id,
				'gender_id' => $gender_id,
				'citizenship_id' => '',
				'region_id' => $region_id,
				'educationdoctype_id' => $educationdoctype_id,
				'foreignlanguage_id' => '',
				'enrollment_date' => $enrollment_date,
				'lastname' => iconv('Windows-1251', 'UTF-8',trim($line[3])),
				'firstname' => iconv('Windows-1251', 'UTF-8',trim($line[4])),
				'surname' => iconv('Windows-1251', 'UTF-8',trim($line[5])),
				'birthdate' => $birthdate_str,
				'passport_ser' => $passport_ser,
				'passport_num' => $passport_num, 
				'passport_data'	=> $passport_data, 
				'passport_birth_place' => '',
				'passport_adress' => iconv('Windows-1251', 'UTF-8',trim($line[12])),
				'adress' => iconv('Windows-1251', 'UTF-8',trim($line[13])),
				'schoolgraduated' => '',
				'educationdocdata' => '',
				'phone' => iconv('Windows-1251', 'UTF-8',trim($line[14])),
				'mobile' => '',
				'email' => '',
				'inn' => '',
				'insurance' => '',
				'pension_certificate' => '',
				'inoculations' => '',
				'moreinfo' => ''));
				$this->Studentinfo->create();
				$this->Studentinfo->save($newstudentinfodata);
				$studentinfo_id = $this->Studentinfo->id;
				//**********************************************************
				// при наличии целевого направления устанавливаем его
				//**********************************************************
				if ($is_targetingintake){
					$newtargetingdata = array('Targetinintake' => array('studentinfo_id' => $studentinfo_id, 
																		'region_id' => $region_id,
																		'info' => 'выгрузка из старой базы'
					));
					$this->Targetingintake->create();
					$this->Targetingintake->save($newtargetingdata);
				}
				//**********************************************************
				// при наличии родителей пишем запись в таблицу relatives
				//**********************************************************
				if ($line[15]){
					$this->Relative->create();
					$newreldata = array('Relative' => array(
					'relativestype_id' => 2,
					'studentinfo_id' => $studentinfo_id,
					'passport_data' => 'НЕТ ДАННЫХ',
					'fio' => iconv('Windows-1251', 'UTF-8',trim($line[15])),
					'job' => iconv('Windows-1251', 'UTF-8',trim($line[16])),
					'jobstatus' =>'',
					'phone' => '',
					'mobile' => '',
					'email' => '',
					'adress' => ''));
					$this->Relative->save($newreldata);
				}
				if ($line[17]) {
					$this->Relative->create();
					$newreldata = array('Relative' => array(
					'relativestype_id' => 1,
					'studentinfo_id' => $studentinfo_id,
					'passport_data' => 'НЕТ ДАННЫХ',
					'fio' => iconv('Windows-1251', 'UTF-8',trim($line[17])),
					'job' => iconv('Windows-1251', 'UTF-8',trim($line[18])),
					'jobstatus' =>'',
					'phone' => '',
					'mobile' => '',
					'email' => '',
					'adress' => ''));
					$this->Relative->save($newreldata);
				}	
				/*
				 * при наличии льгот пишем льготы	
				 */ 
				if ($line[22]){
					$this->PrivilegesStudentinfo->create();
					if ((iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Зона отселения')||
						(iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Постоянно проживающая в зоне отселения')){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 4	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					} else
					if (iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Зона отчуждения'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 8	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					} else	
					if (iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Зона проживания с правом на отселение'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 5	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					} else
					if (iconv('Windows-1251', 'UTF-8',trim($line[17])) == 'Зона с льготным соц.-эконом. статусом'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 6	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					} else		
					if (iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Зона с льготным соц.-эконом. статусом, инвал. 2 гр'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 6	));
						$this->PrivilegesStudentinfo->save($newprivdata);
						$this->PrivilegesStudentinfo->create();
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 1	));					
						$this->PrivilegesStudentinfo->save($newprivdata);							
					} else
					if (iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Инвалид II группы'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 1	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					} else		
					if (iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Инвалид III группы'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 2	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					} else		
					if (iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Инвалид с детства'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 3	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					} else					
					if ((iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Инвалид с детства, Зона с правом на отселение')||
						(iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Зона отселения, Инвалид')){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 3	));
						$this->PrivilegesStudentinfo->save($newprivdata);
						$this->PrivilegesStudentinfo->create();
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 5	));					
						$this->PrivilegesStudentinfo->save($newprivdata);						
					} else		
					if (iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'ребенок-инвалид'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 9	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					} else	
					if (iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Сирота'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 7	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					} else 
					if ((iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Сирота,  зона отселения')||
						(iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Сирота, зона отселения')){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 5	));
						$this->PrivilegesStudentinfo->save($newprivdata);
						$this->PrivilegesStudentinfo->create();
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 7	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					}																		
																									
				}		
				$i++; $j++;				
			}
		}
	//	debug ('всего обработано записей '.$i);
		$this->render('/','blank','addotchisl');			
	}
	/*
	 * добавление студентов из базы access 
	 */
	function addcsv(){
		if (!empty($this->data)) {
			// подгружаем модели 
			$this->loadModel('Studentgroup');
			$this->loadModel('Studentinfo');
			$this->loadModel('Targetingintake');
			$this->loadModel('Relative');
			$this->loadModel('PrivilegesStudentinfo');
			// открываем файл
			$csvfile = fopen($this->data["Student"]["csvfile"]["tmp_name"],"r");
			//читаем первую строку там заголовки
			$line = fgetcsv($csvfile, 10000, ";");
			$i=1; 
			$j=1;
			while(!(feof($csvfile))) {
				$is_targetingintake = false;
				$line= fgetcsv($csvfile, 10000, ";");
				/*
				 *  определяем id группы но нашей базе studentgroup_id
				 */
				// определяем id специальности
				if (iconv('Windows-1251', 'UTF-8',trim($line[0])) == 'Лечебный'){
					$profession_id = 1;	
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[0])) == 'Педиатрический'){
					$profession_id = 2;	
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[0])) == 'Стоматологический'){
					$profession_id = 3;	
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[0])) == 'Медико-профилактический'){
					$profession_id = 4;	
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[0])) == 'Фармацевтический'){
					$profession_id = 5;	
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[0])) == 'Экономики и управления здравоохранением'){
					$profession_id = 6;	
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[0])) == 'Клинической психологии'){
					$profession_id = 7;	
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[0])) == 'Социальной работы'){
					$profession_id = 8;	
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[0])) == 'Биотехнологический'){
					$profession_id = 9;	
				} else {
					debug($i.' Не распознан факультет !!!'.iconv('Windows-1251', 'UTF-8',trim($line[0])));
					continue;
				}								
				// line[0] факультет
				// line[1] курс 
				// line[2] группа
				// определяем xxxx.01.01 из курса 2 курс это 2009 
				if ($line[1] == 1) {
					continue;
				} else if ($line[1] == 2) {
					$year = 2009;
				} else if ($line[1] == 3) {
					$year = 2008;
				} else if ($line[1] == 4) {
					$year = 2007;
				} else if ($line[1] == 5) {
					$year = 2006;
				} else if ($line[1] == 6) {
					$year = 2005;
				} else { 
					debug($i.'Не распознан курс '.$line[1]); 
					continue; 
				}
				// определяем первую часть NUMBER xxx.0x.
				$groupcode = $year.'.0'.$profession_id.'.';
				$tmpgroupnumber = (int)$line[2];
				if ($line[2] < 10) {
					$groupcode = $groupcode.'0'.$tmpgroupnumber;
				}
				else {
					$groupcode = $groupcode.$tmpgroupnumber;
				}			
				
			  	$studentgroup = $this->Studentgroup->find('all', array('conditions' => array('Studentgroup.number' => $groupcode)));
				/*.' '.$studentgroup[0]['Studentgroup']['number']*/
				debug($i.' '.$groupcode.' - '.$studentgroup[0]['Studentgroup']['number']);
				// определяем бюджет внебюджет
				if (iconv('Windows-1251', 'UTF-8',trim($line[20])) =='Коммерческое') {
					$learningtype_id = 2;
				} else
				if((iconv('Windows-1251', 'UTF-8',trim($line[20])) =='Некомеррческое') || 
					(iconv('Windows-1251', 'UTF-8',trim($line[20])) =='Некомерческое') || 
					(iconv('Windows-1251', 'UTF-8',trim($line[20])) =='Некоммерческое') ||
					(iconv('Windows-1251', 'UTF-8',trim($line[20])) =='Некоммерческое (целевое)')) {
					$learningtype_id = 1;
						if (iconv('Windows-1251', 'UTF-8',trim($line[20])) =='Некоммерческое (целевое)'){
							$is_targetingintake = true ;
						}
					}
				// ******************************
				// пишем запись в модель Student
				// ******************************				
				$this->Student->create();
				$newstudentdata = array('Student' => array(
				'learningform_id' => 1,
				'learningtype_id' => $learningtype_id,
				'studentgroup_id' => $studentgroup[0]['Studentgroup']['id'],
				'studentstate_id' => 1,
				'lastname' => iconv('Windows-1251', 'UTF-8',trim($line[3])),
				'firstname' => iconv('Windows-1251', 'UTF-8',trim($line[4])),
				'surname' => iconv('Windows-1251', 'UTF-8',trim($line[5])),
				'unic_number' => ''));
				$this->Student->save($newstudentdata);
				$student_id = $this->Student->id;
				// ******************************
				// записали в Student
				// ******************************
				$enrollment_date = $line[7].'.09.01';
				$this->loadModel('Studentinfo');
				if (iconv('Windows-1251', 'UTF-8',trim($line[27])) == 'ж'){
					$gender_id = 1;
				}else {		$gender_id = 2;	}
				if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Архангельская') {
					$region_id = 12;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Белгородская') {
					$region_id = 3; 
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Брянская') {
					$region_id = 2;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Владимирская') {
					$region_id = 13;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Волгоградская') {
					$region_id = 14;	
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Вологодская') {		
					$region_id = 15;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Воронежская') {		
					$region_id = 7;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Гомельская') {		
					$region_id = 16;
				} else 	if ((iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Калинградская')||(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Калининградская')
						||	(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Калининрадская'))
				{		
					$region_id = 17;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Калужская') {		
					$region_id = 10;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Камчатская') {		
					$region_id = 18;
				} else 	if ((iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Карачаево-Черкесская республика')||(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'КЧР')) {		
					$region_id = 19;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Краснодарский край') {		
					$region_id = 20;
				} else 	if ((iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Красноярский край')||(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Кррасноярский край')) {		
					$region_id = 21;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Курская') {		
					$region_id = 1;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Ленинградская') {		
					$region_id = 22;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Липецкая') {		
					$region_id = 6;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Магаданская') {		
					$region_id = 23;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Московская') {		
					$region_id = 9;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Мурманская') {		
					$region_id = 8;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Нижегородская') {		
					$region_id = 24;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Новгородская') {		
					$region_id = 25;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Новосибирская') {		
					$region_id = 26;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Орловская') {		
					$region_id = 4;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Пермская') {		
					$region_id = 27;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Приморский край') {		
					$region_id = 28;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Беларусь') {		
					$region_id = 29;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Дагестан') {		
					$region_id = 30;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Ингушетия') {		
					$region_id = 31;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Коми') {		
					$region_id = 32;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Мари Эл') {		
					$region_id = 33;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Молдова') {		
					$region_id = 34;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Саха (Якутия)') {		
					$region_id = 35;
				} else 	if ((iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Сев. Осетия-Алания') || (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Сев.Осетия - Алания') ||	(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Республика Северная Осетия - Алания')){		
					$region_id = 36;
				} else 	if ((iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Ростовкая') || (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Ростовская')){		
					$region_id = 37;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Самарская') {		
					$region_id = 38;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Саратовская') {		
					$region_id = 39;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Сахалинская') {		
					$region_id = 40;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Свердловская') {		
					$region_id = 41;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Смоленская') {		
					$region_id = 42;
				} else 	if ((iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Ставропольский')||(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Ставропольский край')) {		
					$region_id = 43;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Тамбовская') {		
					$region_id = 44;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Тверская') {		
					$region_id = 45;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Тульская') {		
					$region_id = 5;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Тюменская') {		
					$region_id = 46;
				} else 	if ((iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Украина')||(iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Украина, Днепропетровская обл.')) {		
					$region_id = 47;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Хабаровский край') {		
					$region_id = 48;
				} else 	if (iconv('Windows-1251', 'UTF-8',trim($line[11])) == 'Ярославская') {		
					$region_id = 49;
				}	
				if ($line[28]) {
					$passport_ser = iconv('Windows-1251', 'UTF-8',trim($line[28]));
				} else {
					$passport_ser = 'НЕТ ДАННЫХ';
				}
				if ($line[29]) {
					$passport_num  = iconv('Windows-1251', 'UTF-8',trim($line[29]));
				} else {
					$passport_num  = 'НЕТ ДАННЫХ';
				}				
				if ($line[30] || $line[31]) {
				$passport_data = iconv('Windows-1251', 'UTF-8',trim($line[30])).' '.iconv('Windows-1251', 'UTF-8',trim($line[31]));				
				} else {
					$passport_data  = 'НЕТ ДАННЫХ';
				}
				if (iconv('Windows-1251', 'UTF-8',trim($line[9])) == 'общее среднее') {
					$educationdoctype_id = 1;
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[9])) == 'среднее специальное') {
					$educationdoctype_id  = 3;
				} else 
				if (iconv('Windows-1251', 'UTF-8',trim($line[9])) == 'высшее') {
					$educationdoctype_id = 5;
				}				
				$birthdate = explode('.', $line[6]);
				$birthdate_str = $birthdate[2].'-'.$birthdate[1].'-'.$birthdate[0];
				debug($birthdate_str);
				// ************************************
				// пишем запись в модель Studentinfo
				// *************************************
				$this->Studentinfo->create();
				$newstudentinfodata = array('Studentinfo' => array(
				'student_id' => $student_id,
				'gender_id' => $gender_id,
				'citizenship_id' => '',
				'region_id' => $region_id,
				'educationdoctype_id' => $educationdoctype_id,
				'foreignlanguage_id' => '',
				'enrollment_date' => $enrollment_date,
				'lastname' => iconv('Windows-1251', 'UTF-8',trim($line[3])),
				'firstname' => iconv('Windows-1251', 'UTF-8',trim($line[4])),
				'surname' => iconv('Windows-1251', 'UTF-8',trim($line[5])),
				'birthdate' => $birthdate_str,
				'passport_ser' => $passport_ser,
				'passport_num' => $passport_num, 
				'passport_data'	=> $passport_data, 
				'passport_birth_place' => '',
				'passport_adress' => iconv('Windows-1251', 'UTF-8',trim($line[12])),
				'adress' => iconv('Windows-1251', 'UTF-8',trim($line[13])),
				'schoolgraduated' => '',
				'educationdocdata' => '',
				'phone' => iconv('Windows-1251', 'UTF-8',trim($line[14])),
				'mobile' => '',
				'email' => '',
				'inn' => '',
				'insurance' => '',
				'pension_certificate' => '',
				'inoculations' => '',
				'moreinfo' => ''));
				$this->Studentinfo->create();
				$this->Studentinfo->save($newstudentinfodata);
				$studentinfo_id = $this->Studentinfo->id;
				//**********************************************************
				// при наличии целевого направления устанавливаем его
				//**********************************************************
				if ($is_targetingintake){
					$newtargetingdata = array('Targetinintake' => array('studentinfo_id' => $studentinfo_id, 
																		'region_id' => $region_id,
																		'info' => 'выгрузка из старой базы'
					));
					$this->Targetingintake->create();
					$this->Targetingintake->save($newtargetingdata);
				}
				//**********************************************************
				// при наличии родителей пишем запись в таблицу relatives
				//**********************************************************
				if ($line[15]){
					$this->Relative->create();
					$newreldata = array('Relative' => array(
					'relativestype_id' => 2,
					'studentinfo_id' => $studentinfo_id,
					'passport_data' => 'НЕТ ДАННЫХ',
					'fio' => iconv('Windows-1251', 'UTF-8',trim($line[15])),
					'job' => iconv('Windows-1251', 'UTF-8',trim($line[16])),
					'jobstatus' =>'',
					'phone' => '',
					'mobile' => '',
					'email' => '',
					'adress' => ''));
					$this->Relative->save($newreldata);
				}
				if ($line[17]) {
					$this->Relative->create();
					$newreldata = array('Relative' => array(
					'relativestype_id' => 1,
					'studentinfo_id' => $studentinfo_id,
					'passport_data' => 'НЕТ ДАННЫХ',
					'fio' => iconv('Windows-1251', 'UTF-8',trim($line[17])),
					'job' => iconv('Windows-1251', 'UTF-8',trim($line[18])),
					'jobstatus' =>'',
					'phone' => '',
					'mobile' => '',
					'email' => '',
					'adress' => ''));
					$this->Relative->save($newreldata);
				}	
				// при наличии льгот пишем льготы	
				if ($line[22]){
					$this->PrivilegesStudentinfo->create();
					if (iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Зона отселения'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 4	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					} else
					if (iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Зона отчуждения'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 8	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					} else	
					if (iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Зона проживания с правом на отселение'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 5	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					} else
					if (iconv('Windows-1251', 'UTF-8',trim($line[17])) == 'Зона с льготным соц.-эконом. статусом'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 6	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					} else		
					if (iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Зона с льготным соц.-эконом. статусом, инвал. 2 гр'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 6	));
						$this->PrivilegesStudentinfo->save($newprivdata);
						$this->PrivilegesStudentinfo->create();
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 1	));					
						$this->PrivilegesStudentinfo->save($newprivdata);							
					} else
					if (iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Инвалид II группы'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 1	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					} else		
					if (iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Инвалид III группы'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 2	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					} else		
					if (iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Инвалид с детства'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 3	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					} else					
					if (iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Инвалид с детства, Зона с правом на отселение'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 3	));
						$this->PrivilegesStudentinfo->save($newprivdata);
						$this->PrivilegesStudentinfo->create();
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 5	));					
						$this->PrivilegesStudentinfo->save($newprivdata);						
					} else		
					if (iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'ребенок-инвалид'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 9	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					} else	
					if (iconv('Windows-1251', 'UTF-8',trim($line[22])) == 'Сирота'){
						$newprivdata = array('PrivilegesStudentinfo' => array(
						'studentinfo_id' => $studentinfo_id,
						'privilege_id' => 7	));
						$this->PrivilegesStudentinfo->save($newprivdata);
					}													
																									
				}		
				$i++; $j++;				
			}
		}
	//	debug ('всего обработано записей '.$i);
		$this->render('/','blank','addcsv');
	}
}
?>